<?php  
  /*
   * 1. Read the value of the user's input in the search text field (the "search string").
   * 2. Read the databse to determine if the search string:
   *  a. Contains a Person's name.
   *  b. Contains a Building name.
   *  c. Contains a Location name.
   * 3. Return the Building corresponding to the search, if there was a result.
   *
   */
  
  $result_building = -1; 
   
  if (isset($_POST['sendToValue'])){
  	$search_string = $_POST['sendToValue'];
  	
  	$db = new PDO('sqlite:supermaps.db');
    $buildings = $db->query("select id, name from Buildings")->fetchAll(PDO::FETCH_ASSOC); //Buildings(id int primary key, name varchar(32), internal_map int, x real, y real, parent_map varchar(32))
    $people = $db->query("select * from People")->fetchAll(PDO::FETCH_ASSOC); //People(id int primary key, name varchar(64), room varchar(32), building int)
    $locations = $db->query("select id, name, building from Locations")->fetchAll(PDO::FETCH_ASSOC); //Locations(id int primary key, name varchar(32), building int, category varchar(32), open time, close time)

    //Initialize the search terms
    $search_tokens = array();
    $token = strtok($search_string, " ");
    while ($token !== false) {
      array_push($search_tokens, $token);
      $token = strtok(" ");
    }
    
    //Search People
    foreach($people as $person) {
      foreach($search_tokens as $st) {
        if (strripos($person['name'], $st) !== false) {
          $result_building = $person['building']-1;
          break;
        }
      }
    }
    
    //Search Locations
    if ($result_building < 0) {
      foreach($locations as $location) {
        foreach($search_tokens as $st) {
          if (strripos($location['name'], $st) !== false) {
            $result_building = $location['building']-1;
            break;
          }
        }
      }
    }
    
    //Search the names of Buildings for a match
    if ($result_building < 0) {
      foreach($buildings as $building) {
        foreach($search_tokens as $st) {
          if (strripos($building['name'], $st) !== false) {
            $result_building = $building['id']-1;
            break;
          }
        }
      }
    }
  	
  }else{
  	$result_building = null;
  }

  //echo json_encode(array("returnFromValue"=>'<a href="javascript:myclick(1)" name="search_link">Search2</a>'));
  echo json_encode(array("returnFromValue"=> $result_building));
?>